package com.jxb.currentLimiting;

/**
 * 计数器限流算法
 *
 * @author jiaobo
 * @date Created in 2024/10/15 21:24
 **/
public class Count {

    public static long timeStamp = System.currentTimeMillis();//当前时间
    public static int reqCount = 0;//初始化计数器
    public static final int limit = 100;//时间窗口内最大请求数
    public static final long interval = 1000 * 60;//时间窗口ms

    public static void main(String[] args) {
        for (int i = 0; i <= 102; i++) {
            if (!limit()) {
                System.out.println(i+"---------限流");
            }
        }
    }
    public static boolean limit() {
        long now = System.currentTimeMillis();
        if (now < timeStamp + interval) {
            //在时间窗口内
            reqCount++;
            //判断当前时间窗口内是否超过最大请求控制数
            return reqCount <= limit;
        }else {
            timeStamp = now;
            //超时后，重置
            reqCount = 1;
            return true;
        }
    }


}
